﻿namespace PropOnline.Stores.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Dynamic;
    using System.Linq;

    public class DynamicDictionary : DynamicObject
    {
        private Dictionary<string, object> obj;

        public DynamicDictionary(IDataRecord dataReader)
        {
            this.obj = new Dictionary<string, object>();
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                if (!dataReader.IsDBNull(i))
                {
                    this.obj[dataReader.GetName(i)] = dataReader[i];
                }
                else
                {
                    this.obj[dataReader.GetName(i)] = null;
                }
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                if (this.obj.Keys.Contains(binder.Name))
                {
                    result = this.obj[binder.Name];
                }
                else
                {
                    result = null;
                }

                return true;
            }
            catch (Exception)
            {
                result = null;
                return false;
            }
        }
    }
}